<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow">
        <a-form size="small" :model="pageData" layout="inline">
          <a-form-item label="回修类型">
            <a-input :style="{ width: '200px' }" class="bacClass" v-model="pageData.dropDownData" allow-clear
              @press-enter="selectHandler" />
          </a-form-item>
        </a-form>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height:99%;width: 100%;z-index:999 ;">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressDragLeaveHidesColumns="true"
          :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height: 100%"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="table.dataList" :columnDefs="tc"
          :localeText="localeText1" :suppressRowClickSelection="true" @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys :page-size-options="pagingList1" :page-size="pagination.pageSize" :current="pagination.page"
      :total="pagination.total" show-total show-jumper show-page-size @change="nextDoRefreshPage"
      @page-size-change="nextDoRefreshSize" style="justify-content: center" />

    <a-drawer :drawer-style="{ zIndex: 9999 }" :mask-closable="false" :width="400" :visible="pageData.showAdd"
      unmountOnClose @ok="sideOk" :ok-loading="saveLoading" @cancel="pageData.showAdd = false" cancel-text="关闭"
      ok-text="保存">
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" :model="dataForm" layout="horizontal">
          <a-form-item :label-col-flex="pageData.labelColFlex" label="回修类型" field="typeName"
            :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '回修类型必填' }]">
            <a-input class="bacClass" v-model="dataForm.typeName" />
          </a-form-item>
          <a-form-item :label-col-flex="pageData.labelColFlex" label="单价" field="price"
            :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '单价必填' }]">
            <a-input-number class="bacClass" v-model="dataForm.price" :precision="2" :min="0" />
          </a-form-item>
          <a-form-item :label-col-flex="pageData.labelColFlex" label="备注" field="remark">
            <a-textarea class="bacClass" v-model="dataForm.remark" allow-clear />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, usePagination, useTableColumn } from '@/hooks/table'
import { ref, reactive, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import 'ag-grid-community/styles/ag-grid.css'
import 'ag-grid-community/styles/ag-theme-alpine.css'
import { localeText } from '@/api/aggridZw'

import { pagingList } from "@/api/paging";
import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

interface paramData {
  id: any
  typeName: string | undefined
  price: number
  remark: string | undefined
}
export default {
  // 回修类型
  name: 'RepairType',
  setup() {
    //隐藏显示头部
    const headerShow = ref<boolean>(true)
    //抽屉保存按钮加载状态
    const saveLoading = ref<boolean>(false)
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      pageLoading: boolean
      theight: number
      rHeight: number | undefined
      labelColFlex: string
    }>({
      showAdd: false,
      sideTitle: '新增回修类型定义',
      dropDownData: '',
      pageLoading: false,
      theight: 0,
      rHeight: 0,
      labelColFlex: '80px',
    })
    //查询列表
    onMounted(() => {
      selectHandler()
    })

    //切换分页
    const nextDoRefreshPage = (val: any) => {
      pagination.page = val
      doRefresh()
    }
    const nextDoRefreshSize = (val: any) => {
      pagination.pageSize = val
      doRefresh()
    }
    const pagination = usePagination(doRefresh)
    const table = useTable()
    function doRefresh() {
      pageData.pageLoading = true
      updateGridState01()
      post({
        url: 'dwQms/reworksType/selectPage',
        data: {
          page: pagination.page,
          limit: pagination.pageSize,
          deleteState: 0,
          typeName: pageData.dropDownData,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.data)
            pagination.setTotalSize(data.total)
            gridOption.value.setRowData(data.data)
            gridOption.value.sizeColumnsToFit()
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }
    //查询
    const selectHandler = () => {
      pagination.page = 1
      doRefresh()
    }
    //------新增、修改页面开始------
    const dataForm = reactive<paramData>({
      id: null,
      typeName: '',
      price: 0,
      remark: '',
    })
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === 'id') {
          dataForm[key] = null
        } else {
          dataForm[key] = ''
        }
      }
      pageData.showAdd = true
      pageData.sideTitle = '新增回修类型定义'
    }
    const editHandler = (record: paramData) => {
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改回修类型定义'
      pageData.showAdd = true
    }

    const formRef = ref<FormInstance>()
    const sideOk = () => {
      saveLoading.value = true
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.sideTitle === '新增回修类型定义') {
            post({
              url: 'dwQms/reworksType/insert',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '新增成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                saveLoading.value = false
              })
          } else {
            post({
              url: 'dwQms/reworksType/update',
              data: [dataForm],
            })
              .then((res: any) => {
                if (res.code === 200) {
                  formRef.value?.resetFields()
                  pageData.showAdd = false
                  Message.success({
                    content: '修改成功',
                    duration: 5000,
                  })
                  doRefresh()
                } else {
                  Message.error({
                    content: res.message,
                    duration: 5000,
                  })
                }
              })
              .finally(() => {
                saveLoading.value = false
              })
          }
        } else {
          saveLoading.value = false
        }
      })
    }
    //------新增、修改页面结束------
    //------删除方法开始------
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        return
      }
      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          post({
            url: 'dwQms/reworksType/delete',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          }).then(({ code, data }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })

              pagination.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
        },
      })
    }
    //------删除方法结束------
    // 表格准备事件
    const tableColumns = useTableColumn([
      {
        title: '序号',
        key: 'serialNo',
        dataIndex: 'serialNo',
        width: 150,
      },
      {
        title: '回修类型',
        key: 'typeName',
        dataIndex: 'typeName',
      },
      {
        title: '单价',
        key: 'price',
        dataIndex: 'price',
      },
      {
        title: '备注',
        key: 'remark',
        dataIndex: 'remark',
      },

      {
        title: '创建人',
        key: 'createName',
        dataIndex: 'createName',
      },
      {
        title: '创建时间',
        key: 'createTime',
        dataIndex: 'createTime',
      },
      {
        title: '最后修改人',
        key: 'updateName',
        dataIndex: 'updateName',
      },
      {
        title: '最后修改时间',
        key: 'updateTime',
        dataIndex: 'updateTime',
      },

      {
        title: '操作',
        key: 'id',
        dataIndex: 'id',
        slotName: 'act',
        width: 150,
        fixed: 'right',
      },
    ])
    const gridOption = ref()
    const colState = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api

      colState.value = params.columnApi
    }
    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      width:160
    }
    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        width: o.width,
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = o.fixed
        obj['cellRenderer'] = {
          template: `<el-button style="color:#165dff;" link @click="a">修改</el-button>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              a,
            }
          },
        }
      }
      return obj
    })
    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const localeText1: any = ref(localeText)
    const pagingList1: any = ref(pagingList)
    const { saveGridState: saveGridState01, updateGridState: updateGridState01 } = saveOrUpdateGridState01('RepairType01', gridOption, colState, tc)
    const onColumnMoved = () => {
      saveGridState01()
    }
    const onColumnResized = () => {
      saveGridState01()
    }
    return {
      saveOrUpdateGridState01,
      saveGridState01,
      updateGridState01,
      onColumnMoved,
      onColumnResized,
      colState,
      pagingList1,
      deleteHandler,
      saveLoading,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      pagination,
      table,
      pageData,
      editHandler,
      selectHandler,
      headerShow,
      nextDoRefreshPage,
      nextDoRefreshSize,
      defaultColDef,
      localeText1,
      tc,
      gridReady,
      gridOption,
    }
  },
  components: { Toolbar,  },
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>
